package com.lambda.plugin


import com.android.builder.core.ApkInfoParser
import com.android.ide.common.process.DefaultProcessExecutor
import org.apache.commons.codec.digest.DigestUtils
import org.gradle.api.Action
import org.gradle.api.Task

class URLUpload implements Action<Task> {
    private final UploadConfig mConfig;

    URLUpload(UploadConfig config) {
        mConfig = config
    }

    @Override
    void execute(Task task) {
        final String taskName = task.name;
        final String buildDir = task.project.buildDir.absolutePath
        final File targetFile;
        if (taskName == "assembleRelease") {
            targetFile = new File(buildDir, "\\outputs\\apk\\app-release.apk");
        } else {
            String variant = taskName.substring(8, taskName.length() - 7).toLowerCase();
            targetFile = new File(buildDir, "\\outputs\\apk\\" + variant + "\\release\\${task.project.name}-${variant}-release.apk");
        }

        if (!targetFile.exists()) return

        HttpURLConnection conn;
        InputStream fis;
        try {
            ApkInfoParser.ApkInfo apkInfo = new ApkInfoParser(
                    new File(mConfig.aapt2),
                    new DefaultProcessExecutor(new UploadLogger())
            ).parseApk(targetFile)

            final String version = "${apkInfo.versionName}.${apkInfo.versionCode}"
            final String timestamp = System.currentTimeMillis();
            final String nonce = UUID.randomUUID().toString().replace('-', '');
            fis = targetFile.newInputStream()
            final int apkSize = fis.available()
            final String md5 = DigestUtils.md5Hex(fis)
            fis.close()
            final String sign = DigestUtils.md5Hex("yyss.${mConfig.secret}${timestamp}${apkInfo.packageName}${version}${md5}${nonce}")

            StringBuilder sb = new StringBuilder(mConfig.url)
            sb.append('?pkg=').append(apkInfo.packageName)
            sb.append('&ver=').append(version)
            sb.append('&timestamp=').append(timestamp)
            sb.append('&nonce=').append(nonce)
            sb.append('&sign=').append(sign)

            conn = new URL(sb.toString()).openConnection()
            conn.connectTimeout = 5000
            conn.readTimeout = 10000
            conn.doInput = true
            conn.doOutput = true
            conn.useCaches = false
            conn.requestMethod = "POST"
            conn.setRequestProperty("Content-Length", String.valueOf(apkSize))

            byte[] buff = new byte[1024]
            int len;

            fis = targetFile.newInputStream()
            while ((len = fis.read(buff)) != -1) conn.outputStream.write(buff, 0, len)
            conn.outputStream.close()

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = conn.inputStream.read(buff)) != -1) baos.write(buff, 0, len)
            conn.inputStream.close()

            println("############# ${new String(baos.toByteArray())}")
        } catch (Exception e) {
            e.printStackTrace(System.err)
        } finally {
            if (conn != null) conn.disconnect()
            if (fis != null) fis.close()
        }
    }
}
